package com.simple.mipclient.client;

import android.content.Intent;
import android.os.Bundle;
import android.os.Message;
import android.os.Messenger;
import android.widget.TextView;

import androidx.activity.EdgeToEdge;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.graphics.Insets;
import androidx.core.view.ViewCompat;
import androidx.core.view.WindowInsetsCompat;

import com.simple.mipc.annotation.IPCProxy;
import com.simple.mipc.annotation.OnApply;
import com.simple.mipc.annotation.Param;
import com.simple.mipc.annotation.Res;
import com.simple.mipc.base.MessengerConnection;
import com.simple.mipc.handler.MessageClientHandler;
import com.simple.mipc.handler.MessageHandler;
import com.simple.mipc.messager.ExecutorManager;
import com.simple.mipc.utils.ProxyUtil;
import com.simple.mipclient.R;
import com.simple.mipclient.client.func.TestFunc;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Timer;
import java.util.TimerTask;
import java.util.UUID;

import lombok.SneakyThrows;

public class MainActivity extends AppCompatActivity {

    private TextView title;

    @IPCProxy
    private TestFunc testFunc;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EdgeToEdge.enable(this);
        setContentView(R.layout.activity_main);
        ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.main), (v, insets) -> {
            Insets systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars());
            v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom);
            return insets;
        });
        title = findViewById(R.id.title);
        // 注册回调方法
        ExecutorManager.getInstance().registerFunc(this);
        // 绑定外部服务
        Intent intent = new Intent("com.example.dialogue.SERVICE_ACTION");
        intent.setPackage("com.simple.dialogue");
        bindService(intent, new MessengerConnection() {
            @Override
            public void initConnected(Messenger messenger) {
                // 创建与外部通信的Messenger MessageClientHandler是回调的必须对象
                Messenger handler = new Messenger(new MessageClientHandler());
                // 自动注入被IPCProxy标记的接口类型的字段
                ProxyUtil.initProxy(MainActivity.this, messenger.getBinder(), handler);
                // 向服务端注册长连接通信，必要操作，否则将无法进行调用
                registerIPC(messenger);
                Timer timer = new Timer();
                timer.schedule(new TimerTask() {
                    @Override
                    public void run() {
                        try {
                            // 调用其它进程的方法
                            testFunc.test(String.format("客户端调用：%s", LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"))));
                        } catch (Throwable throwable) {
                            throwable.printStackTrace();
                        }
                    }
                }, 1000, 1000);
            }
        }, BIND_AUTO_CREATE);
    }

    @SneakyThrows
    private void registerIPC(Messenger messenger) {
        Message obtain = Message.obtain();
        Bundle bundle = obtain.getData();
        bundle.putInt("what", MessageHandler.RESULT_CODE);
        bundle.putString(MessageHandler.MESSAGE_NAME, UUID.randomUUID().toString());
        obtain.replyTo = messenger;
        messenger.send(obtain);
    }

    /**
     * @param msg 必须使用Param注解标记参数名，否则服务端将无法找到该参数，Param中的value必须与服务端的Param对应上
     */
    @OnApply // 必须的注解，54行代码扫描回调方法的时候，需要通过该注解，找到回调的方法
    @Res("/server/test") // 它必须与远程服务端的Res一摸一样，表示该方法是对应Res的回调方法
    private void showResult(@Param("data") String msg) {
        title.setText(msg);
    }
}